import { start_day, end_day, obj_str, find_date_format, cline, uDb, utc_8 } from 'sui';
import { utc_offset } from 'cache';

const set_state = (d) => {
    const state = obj_str(d, "state");
    if (state === "1") {
        d["state"] = "OK";
    }
    else if (state === "0") {
        d["state"] = "NG";
    }
};

const cell_row = (row, tm=false) => {
    const utc = utc_offset();

    row.forEach((d, i) => {
        const tmp = d["time"];

        if (tm && !d["tm"]) {
            d["tm"] = tmp;

            let v = new Date();
            v = "" + v.getTime();
            v = tmp.slice(0, v.length);
            v = new Date(parseInt(v, 10));

            d["time"] = utc_8(v, utc);
        } else {
            d["time"] = utc_8(tmp, utc);
        }

        set_state(d);

        d["index"] = i + 1;
    });

    return row;
};

const load_station = (setStation) => {
    uDb(null, "station/list",
        {
            line: cline(),
        },
        r => {
            const tmp = {};
            r.forEach(d => tmp[d.sn] = d.name);

            setStation(tmp);
        },
        e => setStation(null));
};

const get_init = (optFind) => {
    const s = start_day();
    const e = end_day();

    optFind({
        t_start: s,
        t_end: e,
        time: find_date_format(s, e, "datetime"),
    });
};

export {get_init, load_station, cell_row};
